/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.source.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.thinkgem.jeesite.common.utils.I18nUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.equipment.entity.EleEquipment;
import com.thinkgem.jeesite.modules.equipment.service.EleEquipmentService;
import com.thinkgem.jeesite.modules.source.entity.EleSource;
import com.thinkgem.jeesite.modules.source.entity.EleSourceGroup;
import com.thinkgem.jeesite.modules.source.entity.EleSourceMultimedia;
import com.thinkgem.jeesite.modules.source.entity.image.EleSourceImage;
import com.thinkgem.jeesite.modules.source.entity.image.EleSourceImageGroup;
import com.thinkgem.jeesite.modules.source.entity.video.EleSourceVideo;
import com.thinkgem.jeesite.modules.source.entity.video.EleSourceVideoGroup;
import com.thinkgem.jeesite.modules.source.service.EleSourceGroupService;
import com.thinkgem.jeesite.modules.source.service.EleSourceMultimediaService;
import com.thinkgem.jeesite.modules.source.service.image.EleSourceImageGroupService;
import com.thinkgem.jeesite.modules.source.service.video.EleSourceVideoGroupService;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.OfficeService;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.SwitchUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.templet.service.EleTempletService;

/**
 * 多媒体资源Controller
 * @author unnamed
 * @version 2017-07-10
 */
@Controller
@RequestMapping(value = "${adminPath}/source/eleSourceMultimedia")
public class EleSourceMultimediaController extends BaseController {

	@Autowired
	private EleSourceMultimediaService eleSourceMultimediaService;
	@Autowired
	private EleSourceImageGroupService eleSourceImageGroupService;
	@Autowired
	private EleSourceGroupService eleSourceGroupService;	
	@Autowired
	private EleTempletService eleTempletService;	
	@Autowired
	private EleSourceVideoGroupService eleSourceVideoGroupService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private EleEquipmentService eleEquipmentService;
	@ModelAttribute
	public EleSourceMultimedia get(@RequestParam(required=false) String id) {
		EleSourceMultimedia entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = eleSourceMultimediaService.get(id);
		}
		if (entity == null){
			entity = new EleSourceMultimedia();
		}
		return entity;
	}
	
	@RequiresPermissions("source:eleSourceMultimedia:view")
	@RequestMapping(value = {"list", ""})
	public String list(EleSourceMultimedia eleSourceMultimedia, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		List<User> list = null;
		if(user.isAdmin()) {
			list = systemService.findAllUsers(user);
		}else {
			list = systemService.findAllUsersInCompany(user);
			list.add(UserUtils.getAdminUser());		
		}		
		eleSourceMultimedia.setUsers(list);
		Page<EleSourceMultimedia> page = eleSourceMultimediaService.findPage(new Page<EleSourceMultimedia>(request, response), eleSourceMultimedia); 
		Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);  
		page.setLocale(locale);
		for(EleSourceMultimedia e:page.getList()) {
			e.setGroup(eleSourceGroupService.getGroupById(e.getGroupId()));
		}
		model.addAttribute("page", page);
		return "modules/source/eleSourceMultimediaList";
	}

	@RequiresPermissions("source:eleSourceMultimedia:view")
	@RequestMapping(value = "form")
	public String form(EleSourceMultimedia eleSourceMultimedia, Model model, HttpServletRequest request) {
		if (StringUtils.isEmpty(eleSourceMultimedia.getId())) {
			EleSourceVideoGroup videoGroup = new EleSourceVideoGroup();
			EleSourceImageGroup imageGroup = new EleSourceImageGroup();
			eleSourceMultimedia.setImageGroup(imageGroup);
			eleSourceMultimedia.setVideoGroup(videoGroup);
		} else {
			String imageId = eleSourceMultimedia.getImageId();
			String videoId = eleSourceMultimedia.getVideoId();
			if(!StringUtils.isEmpty(imageId)){
				EleSourceImageGroup tmp = eleSourceImageGroupService.get(imageId);
				String interval = tmp.getInterval();
				tmp.setInterval(Long.parseLong(interval)/1000+"");
				eleSourceMultimedia.setImageGroup(tmp);
			}
			if(!StringUtils.isEmpty(videoId)){
				eleSourceMultimedia.setVideoGroup(eleSourceVideoGroupService.get(videoId));
			}
		}
		Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);  
		model.addAttribute("language", locale.getLanguage());
		if(locale.getLanguage().equals(Locale.CHINESE.getLanguage())){
			model.addAttribute("langCode", locale.getLanguage()+"-cn");
		}else{
			model.addAttribute("langCode", locale.getLanguage());
		}
		model.addAttribute("eleSourceMultimedia", eleSourceMultimedia);
		return "modules/source/eleSourceMultimediaForm";
	}

	@RequiresPermissions("source:eleSourceMultimedia:edit")
	@RequestMapping(value = "save")
	public String save(EleSourceMultimedia eleSourceMultimedia, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		if (!beanValidator(model, eleSourceMultimedia)){
			return form(eleSourceMultimedia, model,request);
		}
		Locale localeA = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);  
		model.addAttribute("language", localeA.getLanguage());
		if(localeA.getLanguage().equals(Locale.CHINESE.getLanguage())){
			model.addAttribute("langCode", localeA.getLanguage()+"-cn");
		}else{
			model.addAttribute("langCode", localeA.getLanguage());
		}
		if("video".equals(eleSourceMultimedia.getType())){
			eleSourceMultimedia.setImageGroup(null);
			if(eleSourceMultimedia.getVideoGroup() == null ||  eleSourceMultimedia.getVideoGroup().getEleSourceVideoList().size() <=0) {
				String locale = I18nUtils.getLocaleStr();
				String msg = "缺少多媒体视频资源";
				if(Global.US.equals(locale)){
					msg = "Lack of multimedia video resources";
				}
				
				addMessage(redirectAttributes, msg);
				model.addAttribute("message", msg);
				return "modules/source/eleSourceMultimediaForm";
			}
		}else{
			eleSourceMultimedia.setVideoGroup(null);
			if(eleSourceMultimedia.getImageGroup() == null || eleSourceMultimedia.getImageGroup().getEleSourceImageList().size() <=0) {
				String locale = I18nUtils.getLocaleStr();
				String msg = "缺少多媒体图片资源";
				if(Global.US.equals(locale)){
					msg = "Lack of multimedia picture resources";
				}
				eleSourceMultimedia.getImageGroup().setInterval(Long.parseLong(eleSourceMultimedia.getImageGroup().getInterval())/1000+"");
				addMessage(redirectAttributes, msg);
			/*	addMessage(redirectAttributes, "缺少多媒体图片资源");*/
				model.addAttribute("message", "缺少多媒体图片资源");
				return "modules/source/eleSourceMultimediaForm";
			}
		}
		EleSourceVideoGroup videoGroup = eleSourceMultimedia.getVideoGroup();
		EleSourceImageGroup imageGroup = eleSourceMultimedia.getImageGroup();
		if (videoGroup != null) {
			List<EleSourceVideo> list = new ArrayList<>();
			for (EleSourceVideo ev : videoGroup.getEleSourceVideoList()) {
				System.out.println(ev.getPath());
				System.out.println(ev.getLiveUrl());
				if(ev.getId() != null && !ev.getDelFlag().equals('1')) {
					list.add(ev);
					if(StringUtils.isEmpty(ev.getPath()) && StringUtils.isEmpty(ev.getLiveUrl())){
						String locale = I18nUtils.getLocaleStr();
						String msg = "多媒体视频资源缺少文件";
						if(Global.US.equals(locale)){
							msg = "Multimedia video resources lack of files";
						}
						addMessage(redirectAttributes, msg);
						model.addAttribute("message", msg);
						return "modules/source/eleSourceMultimediaForm";
					}
				}
				ev.setGroup(videoGroup);
			}
			videoGroup.setEleSourceVideoList(list);
		}
		if(imageGroup != null){
			List<EleSourceImage> list = new ArrayList<>();
			String interval = imageGroup.getInterval();
			imageGroup.setInterval(Long.parseLong(interval)*1000+"");
			
			for(EleSourceImage ev:imageGroup.getEleSourceImageList()){
				if(ev.getId() != null && !ev.getDelFlag().equals('1')) {
					list.add(ev);
					if (StringUtils.isEmpty(ev.getPath())) {
						String locale = I18nUtils.getLocaleStr();
						String msg = "多媒体图片资源缺少文件";
						if(Global.US.equals(locale)){
							msg = "Lack of multimedia picture file";
						}
						imageGroup.setInterval(Long.parseLong(imageGroup.getInterval())/1000+"");
						addMessage(redirectAttributes, msg);
						/*addMessage(redirectAttributes, "多媒体图片资源缺少文件");*/
						model.addAttribute("message", "多媒体图片资源缺少文件");
						imageGroup.setInterval(interval);
						return "modules/source/eleSourceMultimediaForm";
					}
				}
				ev.setGroup(imageGroup);
			}
			imageGroup.setEleSourceImageList(list);
		}
		eleSourceMultimediaService.save(eleSourceMultimedia);

		if(!StringUtils.isEmpty(eleSourceMultimedia.getGroupId())) {
			eleSourceGroupService.deleteFromDB(eleSourceMultimedia.getGroupId());
		}
		
		EleSourceGroup eleSourceGroup = new EleSourceGroup();
		eleSourceGroup.setName(eleSourceMultimedia.getName());
		eleSourceGroup.setVisible("0");
		eleSourceGroup.setType("multimedia");
		boolean noNeedCheck = UserUtils.getSubject().isPermitted("source:eleSourceGroup:check")
                || SwitchUtils.isClose("source:eleSourceGroup:check");
		if(noNeedCheck){
			eleSourceGroup.setDelFlag(EleSourceGroup.DEL_FLAG_NORMAL);
		}else{
			eleSourceGroup.setDelFlag(EleSourceGroup.DEL_FLAG_AUDIT);
		}
		EleSource source = new EleSource();
		source.setId("");
		source.setType("multimedia");
		source.setName("MultimediaGenerated");
		source.setContent(eleSourceMultimedia.getId());
		
		List<EleSource> esList = Lists.newArrayList();
		esList.add(source);
		eleSourceGroup.setEleSourceList(esList);
		System.out.println(JsonMapper.toJsonString((eleSourceMultimedia)));

		
		eleSourceGroupService.save(eleSourceGroup);
		boolean result = true;
		String basePath = Global.getUserfilesBaseDir();
		try {
			result = eleTempletService.createPackageForSourceGroup(eleSourceGroup, basePath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		eleSourceMultimediaService.updateGroupId(eleSourceGroup.getId(), eleSourceMultimedia.getId());
		//System.out.println(eleSourceMultimedia.getImageGroup().getEleSourceImageList().size());
		String locale = I18nUtils.getLocaleStr();
		String msg = "保存多媒体资源成功";
		String msg2 = "保存失败，请重新编辑";
		if(Global.US.equals(locale)){
			msg = "Save multimedia Source success";
			msg2 = "Save failed, please edit again";
		}
		if(result) {
			addMessage(redirectAttributes, msg);
			return "redirect:"+Global.getAdminPath()+"/source/eleSourceMultimedia/?repage";
		} else {
			if(imageGroup != null) {
				String interval = imageGroup.getInterval();
				imageGroup.setInterval(Long.parseLong(interval) / 1000 + "");
			}
			addMessage(redirectAttributes, msg2);
			model.addAttribute("message", msg2);
			return "modules/source/eleSourceMultimediaForm";
		}
	}
	
	@RequiresPermissions("source:eleSourceMultimedia:edit")
	@RequestMapping(value = "delete")
	public String delete(EleSourceMultimedia eleSourceMultimedia, RedirectAttributes redirectAttributes) {
		eleSourceMultimediaService.delete(eleSourceMultimedia);
		String locale = I18nUtils.getLocaleStr();
		String msg = "删除多媒体资源成功";
		if(Global.US.equals(locale)){
			msg = "Multimedia resource deleted";
		}
		addMessage(redirectAttributes, msg);
		return "redirect:"+Global.getAdminPath()+"/source/eleSourceMultimedia/?repage";
	}
	@RequiresPermissions("source:eleSourceMultimedia:edit")
	@RequestMapping(value = "applypublish")
	public String applypublish(EleSourceMultimedia eleSourceMultimedia, RedirectAttributes redirectAttributes,Model model) {
		EleSourceGroup eleSourceGroup = eleSourceGroupService.getGroupById(eleSourceMultimedia.getGroupId());
		if(!EleSourceGroup.DEL_FLAG_NORMAL.equals(eleSourceGroup.getDelFlag())) {
			String locale = I18nUtils.getLocaleStr();
			String msg = "该资源未通过审批，不能发布";
			if(Global.US.equals(locale)){
				msg = "The resource is not approved and can not be released";
			}
			addMessage(redirectAttributes, msg);
			return "redirect:"+Global.getAdminPath()+"/source/eleSourceMultimedia/?repage";
		}

		String basePath = Global.getUserfilesBaseDir();
		try {
			eleTempletService.createPackageForSourceGroup(eleSourceGroup, basePath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		eleSourceMultimediaService.updateGroupId(eleSourceGroup.getId(), eleSourceMultimedia.getId());

		// Edited by jyz (2018.5)
		if(!eleSourceGroupService.resourceFileExistById(eleSourceMultimedia.getGroupId())) {
			String locale = I18nUtils.getLocaleStr();
			String msg = "该资源对应文件不存在，请重新编辑保存后再尝试";
			if(Global.US.equals(locale)){
				msg = "The resource corresponding file does not exist, please re-edit it and try again";
			}
			addMessage(redirectAttributes, msg);
			return "redirect:"+Global.getAdminPath()+"/source/eleSourceMultimedia/?repage";
		}

		EleEquipment eleEquipment = new EleEquipment();
		List<Office> listTree = new ArrayList<>();

        User current = UserUtils.getUser();
       
		List<User> resultList = systemService.getBranchForUserWithSelf(current);
		Set<String> ids = new HashSet<String>();
		for(User temuser:resultList){
			System.out.println(temuser.getLoginName());
			 String officeId = temuser.getOffice().getId();
			 String companyId = temuser.getCompany().getId();
			ids.add(officeId);
			ids.add(companyId);
		}
		List<Office> listOffice = officeService.findList(true);
		
	
		Set<String> officeIds = new HashSet<>();
		Set<String> eqIds = new HashSet<>();
		for(User tmp:resultList){
			EleEquipment eleEquipmentTmp = new EleEquipment();
			eleEquipmentTmp.setCompany(tmp.getCompany());
			eleEquipmentTmp.setOffice(tmp.getOffice());

			List<EleEquipment> listEquipment = eleEquipmentService.findList(eleEquipmentTmp);
			for (EleEquipment equipment : listEquipment) {
				officeIds.add(equipment.getCompany().getId());
				officeIds.add(equipment.getOffice().getId());
				if(eqIds.contains(equipment.getId())){
					continue;
				}
				eqIds.add(equipment.getId());
				Office Office = new Office();
				Office.setId(equipment.getId());
				Office.setParent(new Office(equipment.getOffice().getId()));
				Office.setAddress(equipment.getCode());
				Office.setEmail(equipment.getType().getName());
				Office.setFax(equipment.getWidth() + " X " + equipment.getHeight());
				Office.setRemarks(equipment.getRemarks());
				if("1".equals(equipment.getState())){
					Office.setGrade("在线");
				}else{
					Office.setGrade("离线");
				}
				Office.setPhone("");
				Office.setZipCode(equipment.getName());
				listTree.add(Office);
			}
		}
		System.out.println(listTree.size()+"AAAAAAAAAAAAAAAAAAAAAA");

		Set<String> resultSet = new HashSet<String>();
		for (String oid : officeIds) {
			resultSet.add(oid);
			Office tmp = officeService.get(oid);
			for (int i = 0; i < listOffice.size(); i++) {
				Office item = listOffice.get(i);
				if (item.getId().equals(tmp.getParentId())) {
					System.out.println(item);
					tmp = item;
					i = -1;
					resultSet.add(item.getId());
				}
			}
		}
		for(String oid:resultSet){
			Office item = officeService.get(oid);
			item.setAddress(null);
			item.setEmail(null);
			item.setFax(null);
			item.setRemarks(null);
			item.setGrade(null);
			item.setPhone("display:none;");
			item.setZipCode("");
			listTree.add(item);
		}
			model.addAttribute("list", listTree);
			model.addAttribute("user", current);
			model.addAttribute("eleEquipment", eleEquipment);
			model.addAttribute("eleSourceGroup", eleSourceGroup);
			model.addAttribute("resourcetype", "multimedia");

			return "modules/source/eleSourceGroupPublish";
	}

}